package com.senior.sendmessage.service.impl;

import cn.hutool.core.collection.ListUtil;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONUtil;
import com.senior.sendmessage.entity.CityListDTO;
import com.senior.sendmessage.entity.NewsDTO;
import com.senior.sendmessage.entity.WeatherResultDTO;
import com.senior.sendmessage.service.WeatherService;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.security.SecureRandom;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;

/**
 * @author Baijl
 * @version 0.0.1
 * @date 2021-11-02 15:31
 * @description TODO
 */
@Service
public class WeatherServiceImpl implements WeatherService {
    /**
     * 设置新闻类型缓存列表
     */
    private static Map<String, String> TYPE_MAP;

    static {
        TYPE_MAP = new HashMap<>();
        TYPE_MAP.put("top", "头条");
        TYPE_MAP.put("guonei", "国内");
        TYPE_MAP.put("guoji", "国际");
        TYPE_MAP.put("yule", "娱乐");
        TYPE_MAP.put("tiyu", "体育");
        TYPE_MAP.put("junshi", "军事");
        TYPE_MAP.put("keji", "科技");
        TYPE_MAP.put("caijing", "财经");
        TYPE_MAP.put("youxi", "游戏");
        TYPE_MAP.put("qiche", "汽车");
        TYPE_MAP.put("jiankang", "健康");
    }

    @Value("${key.weatherKey}")
    private String weatherKey;
    @Value("${key.newsKey}")
    private String newsKey;
    @Value("${key.simpleWeatherUrl}")
    private String simpleWeatherUrl;
    @Value("${key.queryWeatherUrl}")
    private String queryWeatherUrl;
    @Value("${key.newsUrl}")
    private String newsUrl;


    @Override
    public CityListDTO queryWeatherList() {
        final HashMap<String, Object> map = new HashMap<>();
        map.put("key", weatherKey);
        final String result = HttpUtil.get(queryWeatherUrl, map);
        return JSONUtil.toBean(result, CityListDTO.class);
    }

    @Override
    public WeatherResultDTO simpleWeatherByCityName(final String id) {
        final HashMap<String, Object> map = new HashMap<>();
        map.put("key", weatherKey);
        map.put("city", id);
        final String result = HttpUtil.get(simpleWeatherUrl, map);
        return JSONUtil.toBean(result, WeatherResultDTO.class);
    }

    @Override
    public NewsDTO newsTop() {
        final HashMap<String, Object> map = new HashMap<>();
        map.put("key", newsKey);
        final Set<String> strings = TYPE_MAP.keySet();
        final ArrayList<String> list = ListUtil.toList(strings);
        final SecureRandom random = new SecureRandom();
        map.put("type", list.get(random.nextInt(list.size())));
        final String result = HttpUtil.get(newsUrl, map);
        return JSONUtil.toBean(result, NewsDTO.class);
    }
}
